package com.yx.cloud.activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.Handler;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.iot.base.bean.message.IotMessage;
import com.iot.base.service.req.DeleteNotificationParam;
import com.iot.base.service.req.GetNotificationParam;
import com.iot.common.utils.Event;
import com.iot.common.utils.LogUtils;
import com.iot.sweeper.AppContext;
import com.yx.cloud.Interface.BounceCallBack;
import com.yx.cloud.Interface.EventForwardingHelper;
import com.yx.cloud.R;
import com.yx.cloud.adapter.MessageAdapter;
import com.yx.cloud.base.BaseActivity;
import com.yx.cloud.databinding.MessageWarningActivityBinding;
import com.yx.cloud.header.NormalBounceHandler;
import com.yx.cloud.utils.Intent_utils;
import com.yx.cloud.utils.LoadProgressDialog;
import com.yx.cloud.utils.RomUtils;
import com.yx.cloud.utils.ToastUtil;
import com.yx.cloud.view.DefaultFooter;
import com.yx.cloud.view.DefaultHeader;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class MessageWarningActivity extends BaseActivity {
    private final static String TAG = "MessageWarningActivity";
    boolean mIsRefresh = false;
    private MessageAdapter messageAdapter;
    private String deviceId;
    private String deviceName;
    private Handler handler;
    private LoadProgressDialog loadProgressDialog;
    private MessageWarningActivityBinding binding;
    private long endTime=0;

    @Override
    public void onCreate() {
        binding = MessageWarningActivityBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        deviceId = getIntent().getStringExtra("device_id");
        deviceName = getIntent().getStringExtra("device_name");
        handler = new Handler();
        initView();

        requestNotification(0, 10, true);
    }

    @Override
    protected void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
    }

    private void initView() {
        binding.tvDeviceMessageTitle.setText(deviceName);
        binding.ivMessageWarningReturn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                Intent_utils.backIntent(MessageWarningActivity.this);
            }
        });

        binding.tvMessageClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                clearDialog(getString(R.string.H_Message_Empty));

            }
        });

        binding.llWarningNoMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                requestNotification(0, 10, true);
            }
        });

        List<IotMessage> messageList = new ArrayList<>();
        messageAdapter = new MessageAdapter(this, messageList);
        messageAdapter.showRightArrow(false);
        binding.lvWarningMessage.setAdapter(messageAdapter);
        messageAdapter.setEnableSwipeDelete(true);
        messageAdapter.setItemListener(new MessageAdapter.ItemListener() {
            @Override
            public void onItemClick(int position) {
            }

            @Override
            public void onItemDelete(int position) {
                List<String> ids = new ArrayList<>();
                ids.add(messageAdapter.getItem(position).getId());
                deleteNotification(ids);
            }

            @Override
            public void onItemCheckChanged(boolean isCheck) {

            }

        });

        binding.blWarningMessage.setBounceHandler(new NormalBounceHandler(), binding.lvWarningMessage);//设置滚动冲突的控制类
        binding.blWarningMessage.setEventForwardingHelper(new EventForwardingHelper() {//自定义事件分发处理
            @Override
            public boolean notForwarding(float downX, float downY, float moveX, float moveY) {
                return true;
            }
        });
        binding.blWarningMessage.setHeaderView(new DefaultHeader(this), binding.flMessageContainer);//设置刷新头，null意味着没有刷新头，不调用该函数意为着空
        binding.blWarningMessage.setFooterView(new DefaultFooter(this), binding.flMessageContainer);
        binding.blWarningMessage.setBounceCallBack(new BounceCallBack() {
            @Override
            public void startRefresh() {
                requestNotification(0, 10, true);
            }

            @Override
            public void startLoadingMore() {
                requestNotification(messageAdapter.getCount(), 10, false);
            }
        });
    }

    public void clearDialog(String dialogTitle) {
        final Dialog dialog = new Dialog(this);
        dialog.setContentView(R.layout.content_centered_dialog);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        dialog.setCanceledOnTouchOutside(false);
        TextView mBtnOutLoginConfirm = dialog.findViewById(R.id.btn_centered_Confirm);
        TextView mBtnOutLoginCancel = dialog.findViewById(R.id.btn_centered_Cancel);
        TextView mTvDialogTitle = dialog.findViewById(R.id.tv_centered_dialogTitle);
        mTvDialogTitle.setText(dialogTitle);
        mBtnOutLoginConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<IotMessage> messages = messageAdapter.getMessageList();
                List<String> mIds = new ArrayList<>();
                for (int i = 0; i < messages.size(); i++) {
                    mIds.add(messages.get(i).getId());
                }
                clearMessage(deviceId);
                dialog.dismiss();
            }
        });
        mBtnOutLoginCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }


    private void clearMessage(String srcId) {
        loadProgressDialog = new LoadProgressDialog(this, false);
        loadProgressDialog.show();
        List<String> srcIds = new ArrayList<>();
        srcIds.add(srcId);

        DeleteNotificationParam param = new DeleteNotificationParam();
        param.setIds(srcIds);
        param.setType(DeleteNotificationParam.DELETE_BY_DEVICE);
        AppContext.getAccountService().deleteNotification(param);
    }

    private void deleteNotification(List<String> mIds) {
        LogUtils.d(" 消息: =======deleteNotification======== :");
        loadProgressDialog = new LoadProgressDialog(this, true);
        loadProgressDialog.show();
        DeleteNotificationParam param = new DeleteNotificationParam();
        param.setIds(mIds);
        AppContext.getAccountService().deleteNotification(param);
    }

    private void requestNotification(int offset, int limit, final boolean isRefresh) {

        mIsRefresh = isRefresh;

        List<IotMessage> messageList = new ArrayList<>();
        LogUtils.d(messageList.size() + " 消息: =======requestNotification======== :" + messageList.size());
        if(isRefresh){
            endTime=System.currentTimeMillis();
        }
        LogUtils.i("endtime : "+ endTime +"  " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(endTime)));
        GetNotificationParam param = new GetNotificationParam();
        param.setOffset(offset);
        param.setLimit(limit);
        param.setDeviceId(deviceId);
        param.setStartTime(0);
        param.setEndTime(endTime);
        AppContext.getAccountService().getNotification(param);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Event event) {
        switch (event.getType()) {
            case Event.MESSAGE_TYPE_GET_MESSAGE_LIST:
                if (event.isResult()) {
                    List<IotMessage> result = (List<IotMessage>) event.getContent();
                    parceMessage(result, mIsRefresh);
                } else {
                    ToastUtil.show(MessageWarningActivity.this, event.getContent().toString(), Toast.LENGTH_SHORT);
                    binding.blWarningMessage.setLoadingMoreCompleted();
                    binding.blWarningMessage.setRefreshCompleted();
                }
                break;
            case Event.MESSAGE_TYPE_DELETE_MESSAGE_LIST:
                if ((Integer) event.getExtra() == DeleteNotificationParam.DELETE_BY_DEVICE) {
                    if (event.isResult()) {
                        LogUtils.i("delete Message Success");
                        ToastUtil.showShort(MessageWarningActivity.this, R.string.U_T_Delete_Ok);
                        loadProgressDialog.dismiss();
                        binding.llWarningNoMessage.setVisibility(View.VISIBLE);
                        Intent intent = new Intent();
                        intent.putExtra("warning", "clear");
                        setResult(RESULT_OK, intent);
                        finish();
                    } else {
                        LogUtils.i("delete Message fail  code: " + event.getContent());
                        loadProgressDialog.dismiss();
                        ToastUtil.showShort(MessageWarningActivity.this, R.string.U_T_Delete_No);
                    }
                } else {
                    if (event.isResult()) {
                        ToastUtil.showShort(MessageWarningActivity.this, R.string.U_T_Delete_Ok);
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                loadProgressDialog.dismiss();
                                requestNotification(0, 10, true);
                            }
                        }, 1000);
                    } else {
                        LogUtils.i("delete Message fail  code: " + event.getContent());
                        loadProgressDialog.dismiss();
                        ToastUtil.showShort(MessageWarningActivity.this, R.string.U_T_Delete_No);
                    }
                }
                break;
        }
    }

    private void parceMessage(List<IotMessage> result, boolean isRefresh) {
        LogUtils.i("getMessageList total--> : " + result.size());
        List<IotMessage> tempList = result;

        if (isRefresh) {
            messageAdapter.updateMessage(tempList);
        } else {
            //可能需要做去重和重定位
            messageAdapter.addMessage(tempList);
        }

        if (tempList == null || tempList.size() == 0) {
            if (messageAdapter.getCount() == 0) {
                binding.llWarningNoMessage.setVisibility(View.VISIBLE);
//                ToastUtil.showShort(MessageWarningActivity.this, R.string.no_data);
//                Intent intent = new Intent();
//                intent.putExtra("warning", "clear");
//                setResult(RESULT_OK, intent);
//                finish();
            } else {
                ToastUtil.showShort(MessageWarningActivity.this, R.string.U_NoMoreRecords);
            }
        } else {
            LogUtils.i("getMessageList size--> : " + tempList.size());
            binding.llWarningNoMessage.setVisibility(View.GONE);
            endTime=tempList.get(tempList.size()-1).getTime();
        }

        binding.blWarningMessage.setLoadingMoreCompleted();
        binding.blWarningMessage.setRefreshCompleted();
    }
}